/*
 *	CHANGE LOG
 *
 *  01.03.07
 *  
 *      11/30/2009 - DW - Closed the data readers when connections are made to the db. 
 *
*/

using System.Security;
using System.Web;
using System.Web.Services;
using DotNetNuke.Data;

namespace ITCrossing
{
	/// <summary>
	/// Summary description for $codebehindclassname$
	/// </summary>
	[WebService(Namespace = "http://tempuri.org/")]
	[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
	public class metaPostRedirectHandler : IHttpHandler
	{

		public void ProcessRequest(HttpContext context)
		{
			string urlKey = context.Request["urlkey"];
			string providerKey = context.Request["key"];
			string intendedUrl = context.Request["IntendedUrl"];

			try
			{
				// Check first to see if this is a request from an account using the old format.  If so, it 
				// will have an IntendedURL QueryString parameter which we'll just redirect to.
				if (!string.IsNullOrEmpty(intendedUrl)) context.Response.Redirect(intendedUrl);

				context.Response.ContentType = "text/html";
				context.Response.ContentEncoding = System.Text.Encoding.UTF8;


				# region Code To Handle WLW Attempt To Download Template

				# region Old Code to Delete
				//// Check first to see if WLW is trying to retrieve a post for identifying the 
				//// template.  
				//// Retrieve the upload URL from the modules settings and overwrite what was passed in
				//// for the intendedUrl.
				//string sSQL =
				//    "SELECT TempInstallUrl FROM {databaseOwner}{objectQualifier}itcMetaPost (nolock) WHERE ItemId = 1";
				//string sURL = null;
				//IDataReader dr =
				//    (IDataReader) DotNetNuke.Data.DataProvider.Instance().ExecuteSQL(sSQL);
				//while (dr.Read())
				//{
				//    sURL = dr["TempInstallUrl"].ToString() + "";
				//}

				//// Delete the entry from the TempInstallUrl field in the database.
				//sSQL =
				//    "UPDATE {databaseOwner}{objectQualifier}itcMetaPost SET TempInstallUrl = '' WHERE ItemId = 1";
				//DotNetNuke.Data.DataProvider.Instance().ExecuteSQL(sSQL);
				# endregion

				// Check to see if we have a custom redirect URL.  We'll base this on the IP Address of the 
				// Request, the ProviderKey and the DateTime of the Request

				string sSQL = "itcMetaPost_Get_Entry_Redirect_URL";
				string sURL;

				object[] methodParams = {providerKey, context.Request.UserHostAddress};

				// Get the URL Key for the Redirect URL.  This sproc will create the URL key if it doesn't exist.
				sURL = DataProvider.Instance().ExecuteScalar(sSQL, methodParams) as string;


				if (!string.IsNullOrEmpty(urlKey) && !string.IsNullOrEmpty(sURL) && sURL != "DefaultBlogURL")
				{
					context.Response.Redirect(sURL);
				}
				else
				{
					// Otherwise, we either have a case where WLW is requesting the page to determine the manifest file
					// or WLW is trying to redirect to the defualt location for the module.  Either way, we pass them on to 
					// metaPostRedirect.aspx to handle the actual redirection.  The aspx redirect file is needed in order to 
					// place a clientside JavaScript file in the page which handles the redirect.
					string blogRedirectVariable = string.Empty;
					if (sURL == "DefaultBlogURL")
					{
						// If the URL is set to DefaultBlogURL, then we are trying to redirect to the default blog location
						// if not, then WLW is just making a request to get the manifest file.
						blogRedirectVariable = "&blogredirect=true";
					}
					context.Response.Redirect("metaPostRedirect.aspx?key=" + HttpUtility.UrlEncode(providerKey) + "&urlkey=" +
											   urlKey + blogRedirectVariable);
					
				}

				# endregion

				
			} catch (SecurityException)
			{
				// if we have a security exception, then we know we're moving around in a 
				// medium trust environment.  We'll just redirect to metaPostRedirect.aspx.
				// Of course, WLW won't be able to download
				// site templates, but there's nothing we can do about it.
					context.Response.Redirect("metaPostRedirect.aspx?key=" + HttpUtility.UrlEncode(providerKey) + "&urlkey=" +
											  urlKey);
			}
		}

		public bool IsReusable
		{
			get
			{
				return false;
			}
		}
	}
}
